package top.hcode.hoj.service;

import com.google.common.util.concurrent.RateLimiter;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author orangej
 * @since 2025/2/16
 */
@Component
@RequiredArgsConstructor
public class RateLimitService {
    private final StringRedisTemplate redisTemplate;

    private final RateLimiter submitAnswerRateLimiter = RateLimiter.create(100);

    public boolean tryAcquireSubmitAnswerBatch() {
        String key = "submit_answer_batch";

        if (!submitAnswerRateLimiter.tryAcquire()) {
            return false;
        }

        return true;
    }

    public boolean tryAcquire(String key, int permits, int maxValue) {
        String lockKey = "rate_limit:" + key + ":" + System.currentTimeMillis() / 1000;
        Long count = redisTemplate.opsForValue().increment(lockKey, permits);
        return count <= maxValue;
    }
}
